//获取应用实例
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    // canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  tapTomon: function() {
    wx.switchTab({
      url: '/pages/my/mon/mon',
    })
  },
  tapTocar: function(){
    wx.navigateTo({
      url: '/pages/my/car/car',
    })
  },
  tapTop: function(){
    wx.navigateTo({
      url: '/pages/my/p/p',
    })
  },
  tapTomon: function(){
    wx.navigateTo({
      url: '/pages/my/mon/mon',
    })
  },
  tapTonull: function(){
    wx.navigateTo({
      url: '/pages/null/null',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
  },
onShow(){
  this.getUserInfo()
},
  getUserInfo: function (e) {
    console.log(e);
    let that = this;
      let token = wx.getStorageSync('token');
      if (token) {
        console.log("如果token存在");
        wx.request({
          url: 'http://localhost:8080/ipark/user/login',
          data: {
            token: token
          },
          success: function (res) {
            console.log("前台token存在，校验token后返回值");
            //如果后台缓存失效了
            if (res.data.TokenExpired) {
              console.log("如果后台缓存已经失效了,小程序清空token和userinfo和openid");
              wx.removeStorageSync("token");
              wx.removeStorageSync("userInfo");
              that.bindGetUserInfo();
            } else {
              console.log("后台缓存中的信息也存在,直接返回");
              wx.setStorageSync("userInfo", res.data.userInfo);
                    const userInfo=wx.getStorageSync("userInfo");
                    that.setData({
                      userInfo:userInfo,
                      hasUserInfo:true
                    });
                    var userid = userInfo.userId;
                    wx.connectSocket({
                      //打开websocket连接
                          url: 'ws://localhost:7000/webSocket?userid='+userid,
                      //打开连接成功
                      success: function (resConnect) {
                        console.log("socket连接成功，resConnect: ")
                        console.log(resConnect)
                        //监听打开事件
                        wx.onSocketOpen(function (resOpen) {
                         console.log(resOpen)
                         //发送消息
                         wx.sendSocketMessage({
                          // data: JSON.stringify({
                          //   number: '123'
                          // }),
                          data:"9#我是28",
                          success: function (resSend) {
                            console.log("resSend:")
                            console.log(resSend)
                          },
                          fail: function (resSendError) {
                            console.log("resSendError: ")
                            console.log(resSendError)
                          }
                        })
                        })
                        wx.onSocketMessage(function (resMessage) {//接收返回消息
                          console.log("resMessage: ")
                          console.log(resMessage);
                        })
                        wx.onSocketError(function (resError) {//出现错误
                          console.log("resError: ")
                          console.log(resError);
                        })
                        wx.onSocketClose(function (resClose) {//连接关闭
                          console.log("resClose: ")
                          console.log(resClose);
                        })
                      },
                      fail: function (resConnectError) {//打开连接失败
                        console.log("resConnectError: "+resConnectError)
                      }
                    })
            }
          }
        });
      }
      //小程序登录,
     else{wx.login({
        success: function (res) {
          if(res.code){          
        wx.getSetting({
          success: res2 => {
            if (res2.authSetting["scope.userInfo"]) {
            wx.getUserInfo({
              success:datas=>{
                console.log("开始获取code和一些加密过的用户信息" + res.code);
                console.log("datas.encryptedData" + datas.encryptedData);
                wx.request({
                  url: 'http://localhost:8080/ipark/user/register',
                  data: {
                    code: res.code,
                    encryptedData: datas.encryptedData,
                    iv: datas.iv
                  },
                 
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function (res) {
                    console.log("后台成功后得到返回值" + res.data);
                    if(res.data.code = 0) {
                      console.log("后台登录错误")
                      wx.hideLoading();
                      wx.showModal({
                        title: "提示",
                        content: "无法登录，请重试",
                        showCancel: false
                      });
                      return;
                    }
                    console.log("存储用户信息token" + res.data.token);
                    console.log("存储用户信息userInfo" + JSON.stringify(res.data.userInfo));
                    wx.setStorageSync("token", res.data.token);
                    wx.setStorageSync("userInfo", res.data.userInfo);
                    const userInfo=wx.getStorageSync("userInfo");
                    that.setData({
                      userInfo:userInfo,
                      hasUserInfo:true
                    });
                    console.log(userInfo)
                    var userid = userInfo.userId;
                    wx.connectSocket({
                      //打开websocket连接
                          url: 'ws://localhost:7000/webSocket?userid='+userid,
                      //打开连接成功
                      success: function (resConnect) {
                        console.log("resConnect: ")
                        console.log(resConnect)
                        //监听打开事件
                        wx.onSocketOpen(function (resOpen) {
                         console.log(resOpen)
                        })
                        wx.onSocketError(function (resError) {//出现错误
                          console.log("resError: ")
                          console.log(resError);
                        })
                        wx.onSocketClose(function (resClose) {//连接关闭
                          console.log("resClose: ")
                          console.log(resClose);
                        })
                      },
                      fail: function (resConnectError) {//打开连接失败
                        console.log("resConnectError: "+resConnectError)
                      }
                    })
                }
              });//request
              }
        })//getuserinfo
      }
    }
   })//getsetting
    }
  }//success
  })}
  },

  setUserInfo: function (userInfo) {
    if (userInfo != null) {
      app.globalData.userInfo = userInfo
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
      console.log('******',userInfo)
      wx.request({
        url: 'http://localhost:8080/ipark/ruser/add',
        data:userInfo,
      //   header: { 
      //     'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
      // },
         method: 'POST',
        success: (result) => {
          //  this.setData({
          //   parkmostList: result.data.data.parkcount
          //  })
          console.log(result)
        },
      });
    }

  },
  
  null:function(){
    wx.showToast({
      title: '努力开发中',
      duration: 1000
    })
  },
})